class register(View):
    """注册"""
    def get(self, request):
        return render(request, 'register.html')  # 显示注册页面

    def post(self, request):
        # 进行注册处理
        # 接收数据
        user_name = request.POST.get('user_name')
        phone = request.POST.get('phone')
        address = request.POST.get('address')
        file_obj = request.FILES.get('photo')
        user_pwd = request.POST.get('user_pwd')

        # 校验用户是否重复
        try:
            user = User.objects.get(phone = phone)
        except User.DoesNotExist:
            # 用户名不存在
            user = None

        if user:
            return render(request, 'register.html', {'errmsg': '用户已存在'})

        # 进行业务处理：进行用户注册

        # 构造文件名以及文件路径
        file_name = './static/images/' + user_name + '_' + str(int(time.time())) + '.' + file_obj.name.split('.')[
            -1]
        User.user_name = user_name
        User.phone = phone
        User.address = address
        User.password = user_pwd
        User.Image = file_name[1:]
        User.save()
        with open(file_name, 'wb+') as f:
            f.write(file_obj.read())

        # 返回应答,跳转首页
        return redirect(reverse('goods:index'))


class LoginView(View):
    """登录"""
    def get(self, request):
        # 显示登录页面
        return render(request, 'login.html')

    def post(self, request):
        # 接受数据
        phone = request.POST.get('phone')
        user_pwd = request.POST.get('pwd')

        # 业务处理: 登陆校验
        user = User.objects.get(phone=phone, user_pwd=user_pwd)
        if user is not None:
            # 登录并记录用户的登录状态
            user_id = user.user_id
            user.is_active = 1
            user.save()
            request.session['login_status'] = 1
            request.session['user_id'] = user_id

            # 获取登录后所要跳转到的地址, 默认跳转首页
            next_url = request.GET.get('next', reverse('goods:index'))

            #  跳转到next_url
            response = redirect(next_url)  # HttpResponseRedirect

            # 回应 response
            return response

        else:
            return render(request, 'login.html', {'errmsg': '用户名或密码错误'})


class LogoutView(View):
    """退出登录"""
    def get(self, request):
        user_id = request.session.get('user_id')
        user = User.objects.get(user_id = user_id)
        user.is_active = 0
        request.session.flush()
        return redirect(reverse('goods:index'))


class Profile(View):
    """用户中心-信息页"""
    def get(self, request):
        # 获取个人信息
        status = request.session.get('login_status')
        if status:
            user_id = request.session.get('user_id')
            user = User.objects.get_default_address(user_id=user_id)
            return render(request, 'profile.html')
        else:
            return redirect('/login/')